var host = window.location.host
ws = new WebSocket("ws://" + host.replace(":8080","") + ":8081/ws");

ws.onopen = function(e) {
    echo("连接成功！");
        //这里再次同步一次
        var data = {}
        getHistory()
        if (User.name != ''){
            data.name = User.name
            data.sign = User.sign
            data.header = User.header
            data.type = "LoginSuccess"
            messageJson = json(data);
            ws.send(messageJson)   
        }


}
ws.onclose = function(evt) {
    echo("连接关闭");
    ws = null;
}
ws.onmessage = function(e) {
    //这里再次同步一次
    getHistory()
    //let t = lastMsgTime
    data = $.parseJSON(e.data);
    if(data.type == "IPLIMIT"){
        $("body").html("<h1 class='IPLIMIT'>" + data.data + "</h1>")
        ws = null;
    }else if(data.type == "QL"){
        msg = data.data
        if(msg.Mtype == "UserList"){
            UserList(msg.data)
            Sounds(1)
        }else if(msg.Mtype == "IPLIMIT"){
            $("body").html("<h1  class='IPLIMIT'>" + msg.data + "</h1>")
            ws = null;
        }else if(msg.Mtype == "SL"){
            let Sign = msg.Sign == User.sign ? msg.To:msg.Sign
            if(ContactIng.Sign != Sign){
                contactList[getContactListIndex(Sign)].NoReadMsg.push(msg)
                UpdateContactList(1)
            }else{
                contactList[getContactListIndex(Sign)].Msg.push(msg)
                UpdateContactList(1)
            }
            if( msg.Sign != User.sign){
                Sounds(0)
            }
        }else{
            if(ContactIng.Sign != "QL"){
                contactList[0].NoReadMsg.push(msg)
                UpdateContactList(1)
                Sounds(0)
            }else{ 
                if(msg.IsHistory == "yes"){
                        if(!QMsgHasGet(data.data)){
                            contactList[0].Msg.push(msg)
                            UpdateContactList(1)
                            setTimeout(()=>{
                                Sounds(0)
                            },1000)
                        }
                }else{
                    contactList[0].Msg.push(msg)
                    UpdateContactList(1)
                    if( msg.Sign != User.sign){
                        Sounds(0)
                    }
                }
                //return hsitoryHasShow == true ? QL(msg) : setTimeout(()=>{QL(msg) },500) //解决历史缓存消息与离线消息与实时消息同步问题
            }
        }
    }else if (data.type == "OpenAnalysisSql"){
        $(".AnalysisSqlResult").html(data.data)
        
        //设置高度
        // $(".showProfile").parent(".tableBox").css({height:$(".showProfile").height() + 20 +"px"})
        // $(".explainSql").parent(".tableBox").css({height:$(".explainSql").height()+"px"})
        // $(".showSelectRes").parent(".tableBox").css({height:$(".showSelectRes").height()+"px"})
        setTimeout(()=>{
            let tableBoxTop = 0
            $(".tableBox").each((i)=>{
                tableBoxTop += 50
                $(".tableBox").eq(i).css({top: tableBoxTop+ "px"})
                tableBoxTop +=$(".tableBox").eq(i).height()
            })
            setTimeout(()=>Drag(),100)
        },100)
    }else if (data.type == "GETALLDATABASES"){
        OpenAnalysisSql(data.data)
    }else if (data.type == "mysql"){
        id("Mysqlbox").innerHTML = data.logs
    }else if(data.type == "ADDDIR"){
        if(data.path.length > 0 && data.status == "yes"){
            let Data = {};
            Data.type = "GetPathInfo";
            Data.data = data.path;
            ws.send(json(Data))
        }else{
            layer.msg("创建失败！" + data.body)
        }
    }else if(data.type == "DELDIR"){
        if(data.status == "no"){
            layer.msg("删除失败")
        }else{
            let Data = {};
            Data.type = "GetPathInfo";
            Data.data = data.path;
            ws.send(json(Data))
        }
    }else if(data.type == "api"){
      apiBodyBox = ace.edit("apiBodyBox",{
            wrap: true,
            showInvisibles:false,
            showPrintMargin: false,
            enableBasicAutocompletion: true,
            enableSnippets: true,
            enableLiveAutocompletion: true,
            useSoftTabs:false,
            tabSize:4,
            keyboardHandler:'sublime',
            theme:"ace/theme/monokai"
    });
    apiBodyBox.resize();
   // editor.setTheme("ace/theme/monokai");
    
   let header = ""
   if(data.header){
       for(k in data.header){
           header +=  k + "：  " + data.header[k] + "\n"
       }
   }
   let backStr = header +  data.body
   apiBodyBox.setValue(backStr,-1)  
   if(showPerformance){
    Performance(data.hs,data.url)
   }
   apiBodyBox.getSession().setMode("ace/mode/" + ApiResponsModel);


        // $(".apiBody pre").html(data.body)
        // let header = "<hr/>"
        // if(data.header){
        //     for(k in data.header){
        //         header += "<p style='color:#000;font-size:14px;font-weight:normal;'>" + k + "：  " + data.header[k] + "</p>"
        //     }
        // }
        // Performance(data.hs,data.url)
        // $(".apiBody pre .HaoShi").html($(".apiBody pre .HaoShi").html() + header)

    }else if(data.type == "STRREPLACE"){
        $(".apiBody pre .jieguo").html(data.body + $(".apiBody pre .jieguo").html())
    }else if(data.type == "STRSEARCH" || data.type == "DIRSEARCH"){
        if(data.jindu == "yes" && data.status == "no"){
            $(".apiBody pre .jindu").html(data.path)
        }else if(data.status == "no" && data.jindu == "runing"){
            $(".apiBody pre .progress-span").html(data.progress)
            $(".apiBody pre  progress").val(data.progress)           
        }else if(data.status == "no" && data.jindu == "yes"){
            $(".apiBody pre .jindu").html(data.body)
        }else if(data.status == "yes" && !data.haoshi){
            $(".apiBody pre .jieguo").append(data.body)
        }else{
            $(".apiBody pre .jindu").html(data.body)
        }
    }else if(data.type == "GetFileInfo"){
        let model = $("#debugModel option:selected").val()
        let path = data.path
        //网页 api模式
        //if($.inArray(model,fileSystemModels) != -1){
            if(data.status == "no"){
                alert(data.body)
                $(".fileDir").html("")
                $("#code").attr("readonly","readonly")
                if(fileOpenLists.length <= 0){
                    $(".codeBox").hide("slow")
                }
                return
            }

            //准备打开列表
            //先判断目录是否已经打开
            if($.inArray(path,fileOpenLists) == -1){
                fileOpenLists.push(path)
            }
            iniFileOpenLists(path)
            //给关闭按钮添加事件
            $(".fileLists >button .close").bind("click",function(event){
                event.stopPropagation();//阻止冒泡
                removeEdit(this)
            })
            $("#code").removeAttr("readonly")
            $("#codeBoxWidthSet").val(parseInt(PageWidth) / 2)
            $("#codeBoxWidthSet").attr("max",parseInt(PageWidth))
            $(".fileDir").html(data.path)
            codeMain = ace.edit("codeMain",{
                wrap: true,
                showInvisibles:false,
                showPrintMargin: false,
                enableBasicAutocompletion: true,
                enableSnippets: true,
                enableLiveAutocompletion: true,
                useSoftTabs:false,
                tabSize:4,
                keyboardHandler:'keybinding-sublime',
                theme:"ace/theme/monokai"
        });

        codeMain.focus(); 
        codeMain.gotoLine(openLine,0, true);
        openLine = 1
   

        codeMain.commands.addCommand({
            name: 'myCommand',
            bindKey: {win: 'Ctrl-s'},
            exec: function(editor) {
                Code()
                layer.msg("代码保存成功！")
            },
            readOnly: false // 如果不需要使用只读模式，这里设置false
        });
        codeMain.resize();
       // editor.setTheme("ace/theme/monokai");
        codeMain.setValue(data.body,-1)
        Lang(codeMain,data.path)
        $("#codeMain").css({
            width: $(".codeBox").width + "px",
            height: PageHeight - 300 + "px"
        })
        //解决第一次打开文件闪移问题
        if(fileOpenLists.length <= 1 && openEditCounts == 0){
            //在渲染一次
            openEdit()
            openEdit()
            openEditCounts++
        }
    }else if(data.type == "GetPathInfo"){
        if(data.status == "no"){
            $(".apiBody pre").html("<h1>" + data.body +"</h1>" )
            return 
        }
        $(".dirLists").html(data.body)
        if (data.path != "disk") {
            $(".nowPath").html(data.path)
        }else{
            $(".nowPath").html("")
        }
        bindDel()
    }else if(data.type == "IPTOCITY" || data.type == "TIMETODATE"){
        $(".apiBody pre").html("<h1>" + data.body +"</h1>" )
    }else if(data.type == "REGXP"){
        $("#regStr").val( data.body)
        updateModelsUrlValues();
    }else if(data.type == "PressureTest"){
        if (data.status == "err"){
            $("#DeBug").css("pointer-events","auto")
            ShowMsg(data.body)
        }else if (data.finish) {
            $(".apiBody pre .jindu").append(data.body)
            var progress = (parseFloat(data.finish) / parseFloat(data.total)  * 100).toFixed(2)
            $(".apiBody pre .JieGuo .progress-span").html(progress)
            $(".apiBody pre .JieGuo progress").val(progress)
            var n = parseInt($(".apiBody").innerHeight()) / 18 ;
            if(parseInt(data.finish) > n){
                var top = (parseInt(data.finish) - n) * 18;
                $(".apiBody pre .jindu").css("top", "-" + top + "px")
                if (parseInt(data.finish) == parseInt(data.total)){
                    $(".apiBody pre .jindu").css("top", "-" + (top + 75) + "px")
                    setTimeout(function(){
                        $(".apiBody pre .jindu").append('<button onclick="readAll()" class="readAll">查看全部</button>')
                        if($(".isAutoYaCe").prop("checked")){
                            layer.msg("5秒后即将自动压测!")
                            setTimeout(()=>{DeBug()},5000)
                        }
                    },100)
                }
            }
        }else{
            $(".apiBody pre .JieGuo").append(data.body)
            $("#DeBug").css("pointer-events","auto")
            if(showPerformance){
                yaLiPerformance(data.now,data.model,data.url)
            }
        }
    }
}
ws.onerror = function(evt) {
    echo("ERROR: " + evt.data);
}
